<template>
    <div class="pie-chart">
        <el-card>
            <template #header>
                <div class="card-header">事件统计情况</div>
            </template>
            <div class="chart" style="width:600px;height:400px"></div>
        </el-card>
    </div>
</template>
<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, nextTick, watch } from 'vue'

const { pieValue } = defineProps({
    pieValue: {
        type: Object,
    }
});

const option = ref({
    legend: {
        top: 'bottom'
    },
    series: [
        {
            type: 'pie',
            radius: [50, 250],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
                borderRadius: 8
            },
            data: [{
                value: 20,
                name: '碰撞'
            },
            {
                value: 14,
                name: '刮擦'
            },
            {
                value: 4,
                name: '其他'
            },
            {
                value: 6,
                name: '失火'
            }, {
                value: 7,
                name: '翻车'
            }, {
                value: 5,
                name: '碾压'
            }],
        }
    ]
});

onMounted(async () => {
    await nextTick();
    let chart = echarts.init(document.querySelector('.chart'));
    chart.setOption(option.value);
    updateChartData()
    console.log(pieValue)
});

watch(() => pieValue, (newPieValue, oldPieValue) => {
    // 监听 pieValue 的变化，当其变化时更新图表数据
    if (newPieValue) {
        // 将对象转换为 ECharts 所需的数据格式
        const newData = Object.entries(newPieValue).map(([name, value]) => ({
            name: name,
            value: value
        }));
        // 更新图表的数据
        option.value.series[0].data = newData;
        // 触发图表更新
        let chart = echarts.init(document.querySelector('.chart'));
        chart.setOption(option.value);
    }
});
// 更新图表数据函数
function updateChartData() {
    if (pieValue) {
        // 将对象转换为 ECharts 所需的数据格式
        const newData = Object.entries(pieValue).map(([name, value]) => ({
            name: name,
            value: value
        }));
        // 更新图表的数据
        option.value.series[0].data = newData;
    }
}
</script>

<style lang="scss" scoped>
.pie-chart {
    z-index: 1000;
    position: fixed;
    bottom: 50%;
    right: 50%;
    transform: translate(50%, 50%);

    ::v-deep .el-card__body {
        height: 558px;
        width:600px;
        
        .chart {
            height: 100%;
        }
    }
}
</style>
